<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/7/17
 * Time: 下午4:16
 */

namespace app\mall\logic;


use extend\Functions;
use extend\STATUS_CODE;

class Withdraw
{
    /**
     * @purpose 获取提醒记录
     * @param int $uid
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function items (int $uid, int $page = 1, int $size = 50): array
    {
        $model      =   new \app\model\Withdraw();
        $result     = $model
            ->where('uid', $uid)
            ->field('id,quota,status,message,odd_numbers,FROM_UNIXTIME(create_at, \'%Y-%m-%d %H:%i:%s\') as create_time')
            ->page($page, $size)
            ->order('create_at desc, status asc')
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
    /**
     * @purpose 申请提现
     * @param int $quota
     * @param int $uid
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function withdraw (int $quota, int $uid): array
    {
        if ($quota < 0) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '参数错误!'
            );
        }
        $member     = new \app\model\Member();
        $withdraw   = new \app\model\Withdraw();
        $balance    = $member
            ->where('uid', $uid)
            ->value('balance');
        if ($balance < $quota) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '余额不足!'
            );
        }
        $withdraw_data = [];
        $withdraw_data['uid'] = $uid;
        $withdraw_data['quota'] = $quota;
        $withdraw_data['status'] = 1;
        $withdraw_data['odd_numbers'] = date('YmdHis', time()).Functions::random(4);
        RE_ODD_NUMBER:
            $withdraw_data['odd_numbers'] = date('YmdHis', time()).Functions::random(4);
        if ($withdraw->total(['odd_numbers' => $withdraw_data['odd_numbers']]) > 0) {
            goto RE_ODD_NUMBER;
        }
        $member->startTrans();
        $balance_action = $member
            ->where('uid', $uid)
            ->setDec('balance', $quota);
        $frozen_action  = $member
            ->where('uid', $uid)
            ->setInc('frozen', $quota);
        $withdraw_result = $withdraw
            ->data($withdraw_data)
            ->save();
        if ($balance_action && $frozen_action && $withdraw_result) {
            $member->commit();
            return Functions::result(
                STATUS_CODE::SUCCESS,
                '申请成功,系统正在处理中,请耐心等待...！'
            );
        }
        $member->rollback();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $withdraw_result
        );
    }
}